package com.jinzheng.qianhai.commont;
import com.jinzheng.qianhai.util.HexUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelOutboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import lombok.extern.slf4j.Slf4j;

/**
 * netty服务端出参
 */
@Slf4j
public class DiscardOutServerHandler extends ChannelOutboundHandlerAdapter {

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        byte[] byteValue = (byte[]) msg;
        boolean checkCode = checkCode(byteValue);
        System.out.println("回写客户端数据校验结果："+checkCode);
        if(checkCode){
            log.info("回写消息: {}", HexUtils.toHexString(byteValue));
            super.write(ctx, "from server: " + byteValue, promise);
            //不能释放ByteBuf，因为会导致消息缓冲区失效
            //buf.release();
        }
    }


    /**
     * 数据校验
     * @param bytes
     * @return
     */
    public static boolean checkCode(byte[] bytes){
        if(null==bytes || bytes.length < 25 || bytes[0]!=0x23 || bytes[1]!=0x23){
            log.warn("数据格式错误：{}", org.apache.tomcat.util.buf.HexUtils.toHexString(bytes));
            return false;
        }
        byte checkCode = 0x00;
        for (byte bt:bytes){
            checkCode ^= bt;
        }
        if(checkCode!=0x00){
            log.warn("数据校验错误：{}", org.apache.tomcat.util.buf.HexUtils.toHexString(bytes));
            return false;
        }
        return true;
    }

}
